import logging
import os
import sys

sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.conf import settings
from qiniu import Auth, BucketManager, build_batch_delete

_LOGGER = logging.getLogger(__name__)
EXPIRE_TIME = 60*5  # 5分钟

Q = Auth(*(settings.QINIU_KEY_PAIR))


def get_token(bucket=settings.CHAT_BUCKET_NAME, expires=EXPIRE_TIME):
    token = Q.upload_token(bucket, expires=expires)
    return token


def get_private_url(url, expires=3600):
    return Q.private_download_url(url, expires)


def fix_image_url(url, expires=3600):
    if not url:
        return url
    if url.startswith('http'):
        return get_private_url(url, expires)
    if not url.startswith('/'):
        url = '/' + url
    return get_private_url(settings.QINIU_DOMAIN + url, expires)


def gen_thumbnail_url(url):
    magic_var = '?imageMogr2/thumbnail/200x200'
    url += magic_var
    return fix_image_url(url)





